package com.aptemo.webetek.server.handlers;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.InvitationAction;
import com.aptemo.webetek.client.enums.EnumUserRole;
import com.aptemo.webetek.client.enums.EnumUserStatus;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.UserBean;

public class InvitationHandler
		extends ActionHandler<InvitationAction, UserBean>
{

	public InvitationHandler(DataStoreAPI dbAPI)
	{
		super(dbAPI);
	}

	public Class<? extends Action<?>> getActionType()
	{
		return InvitationAction.class;
	}

	@Override
	public UserBean invoke(InvitationAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();

		if (!utils.isTeamEditor(action.getTeamId()))
		{
			throw new BackendException(EErrorCodes.NOT_TEAM_EDITOR);
		}

		// 
		if (utils.isTeamMember(action.getTeamId(), action.getEmail()))
		{
			throw new BackendException(EErrorCodes.PLAYER_EXISTS_ALREADY);
		}

		// create new player
		UserBean ub = dataService.createPlayer(action.getTeamId(), action.getEmail(), EnumUserStatus.INVITED, EnumUserRole.GAMER, 0.0);

		// TeamBean team = dataService.getTeam(action.getTeamId());
		// if (team.isNotifications())
		{
			// TODO email notification...
			String content = "'" + ub.getEmail() + "' " + action.getMessage();
			// confirm link
			String path = this.getServletUrl();
			String link = path + "/webetek/invite?id=" + ub.getKey() + "&method=approve";
			content += "\r\n\r\n" + link;

			String farewell = "\r\n\r\n\r\n" + action.getFarewell();
			content += farewell;

			content += "\r\n\r\n";
			content += "\r\n" + path + "#group-" + action.getTeamId() + "";

			createEmailSenderTask("", ub.getEmail(), "", action.getSubject(), content);
		}

		return ub;
	}

}
